package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.interfaces.UserInviteService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.SUserInviteMapper;
import cn.huiyunche.base.service.model.SUserInvite;
import cn.huiyunche.base.service.model.SUserInviteExample;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.UserVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserInviteServiceImpl implements UserInviteService {
    private static final Logger logger = LoggerFactory.getLogger(UserInviteServiceImpl.class);

    @Autowired
    private SUserInviteMapper sUserInviteMap = null;

    @Autowired
    private UserService userService = null;

    @Override
    public SUserInvite queryUserInvite() throws Exception {
        UserVo user = this.getUserService().getCurrentUserVo();
        logger.info("current userid : {}", user.getId());
        SUserInviteExample example = new SUserInviteExample();
        example.createCriteria().andUserIdEqualTo(user.getId());
        List<SUserInvite> sInvites = this.getSUserInviteMapper().selectByExample(example);
        if (CollectionUtils.isNotEmpty(sInvites) && sInvites.size() > 0) {
            SUserInvite sInvite = sInvites.get(0);
            Date priod = DateUtils.addMonths(sInvite.getCreateTime(), sInvite.getInviteCodePriod());
            if (new Date().before(priod)) {
                return sInvites.get(0);
            } else {
                logger.info("Verification code has been validity");
                throw new BusinessException("邀请码已过有效期");
            }
        }
        return null;
    }

    private SUserInviteMapper getSUserInviteMapper() {
        return this.sUserInviteMap;
    }

    private UserService getUserService() {
        return this.userService;
    }

}
